define([
    'jquery',
    "UtilDir/util",
    "combotree",
    "Validate",
//	"static/core/platform/global/base",
    "EasyUI","EasyUI-lang"
], function($,Util,Combotree){
	var getDivisionController = function () {
        return getServer() + "/platform/org/divisions/";
   };
    var PUBLIC_KEY = "";
    var LOGIN_CAPTCHA = false;
	var init = function () {
	    initSecret();
        // 初始化布局相关
          initLayout();
        // 初始化事件
        initEvent();
		formValidator();
		initdivision();
    };
    var initSecret = function(){
        PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCHoRwcuCKprPUhZh3IG6+NxfHiIgXp24aMJ6I69iJMKtInUgymmdB4RcZ7FfX2yRUj/aiXzGPYTyVErLo2fb88Yi/YOse3S/j31OjswYe/1X4PsH5Jo52PKNtjs151nVc8UzQ8mHRKZzKLH+ySRsZLTWVs7nIwDlvcqydj/NI4ZwIDAQAB";
        LOGIN_CAPTCHA = $("#isCaptcha").val()
    };
    // 初始化布局相关
    function initLayout() {
    	// 触发响应式布局的关键点（浏览器宽度）
    	var bigSize = 1440,
    		smallSize = 650;
    	// 响应式布局
        response();
        // 布局设置好后再显示整个页面，防止页面抖动
        $('.register-body').fadeIn(100);
    	// 动态计算宽高
//      calculatePosition();
//
//      // 页面触发resize事件时，重新布局
//      $(window).resize(function(){
//      	response();
//      	calculatePosition();
//      });

        // 响应式布局
        function response(){
            var bodyWidth = $('body').width();
            if(bodyWidth > bigSize){
                $('.style-change').attr('href', getServer() + '/static/fwcore/platform/page/register/css/register-large-screen.css');
            }
            else if(bodyWidth <= bigSize && bodyWidth >= smallSize){
                $('.style-change').attr('href', getServer() + '/static/fwcore/platform/page/register/css/register-medium-screen.css');
            }else{
            	$('.style-change').attr('href', getServer() + '/static/fwcore/platform/page/register/css/register-small-screen.css');
            }
        }

    }
	var formValidator = function(){
		//用户名必须需包含数字和大小写字母中至少两种
//	    $.validator.addMethod("passwordrule", function(value, element) {
//	        var userblank = /^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)[0-9A-Za-z]{6,20}$/;
//	        return this.optional(element) ||(userblank.test(value));
//	    }, "需包含数字和大小写字母中至少两种字符的6-20位字符");
		$.validator.addMethod("mobile", function (value, element) {
		    var length = value.length;
		    return this.optional(element) || (length == 11 && /^1(3|4|5|6|7|8|9)\d{9}$/.test(value));
			//return this.optional(element) || (length == 11);
		}, "手机号码格式错误!");
		$.validator.addMethod("idCard", function (value, element) {
		    var length = value.length;
		    return this.optional(element) || (length == 18 && /^(([1][1-5])|([2][1-3])|([3][1-7])|([4][1-6])|([5][0-4])|([6][1-5])|([8][1-2]))\d{4}(([1][9]\d{2})|([2]\d{3}))(([0][1-9])|([1][0-2]))(([0][1-9])|([1-2][0-9])|([3][0-1]))\d{3}[0-9xX]$/.test(value));
			//return this.optional(element) || (length == 11);
		}, "身份证号格式错误!");
		$("#web_register_form").validate({
			rules: {
                userLevel: {
                	required : true
                },
				userName : {
					required :true,					
					mobile: true
				},
                passWord : {
                    required :true,
                    minlength:6,
                    maxlength:20,
//                  passwordrule: true
                },
                confirmPwd : {
                    required :true,
                    minlength:6,
                    maxlength:20,                 
//              	equalTo:"#passWord"
                },
//              mobilePhone : {
//                  required :true,                   
//                  mobile: true
//              },
                relName : {
                    required :true,
                    maxlength:20
                },
                idNumber : {
                    required :true,
                    idCard: true
                },
                userType : {
                    required :true
                },
                division : {
                    required :true
                }
			},
			messages: {
                userLevel: {
                    required : "用户等级不允许为空"
                },
                userName : {
					required:"用户名不允许为空!",
					maxlength:"用户名长度不可以超过20"
				},
                passWord : {
                    required:"密码不允许为空!",
                    minlength:"请输入最少为6为字符",
                    maxlength:"密码长度不可以超过20",
                    passwordrule: "需包含数字和大小写字母中至少两种字符的6-20位字符"
                },
                confirmPwd : {
                    required:"密码不允许为空!",
                    minlength:"请输入最少为6为字符",
                    maxlength:"密码长度不可以超过20",
                    equalTo:"两次密码输入不一致"
                },
//              mobilePhone : {
//                  required:"手机号不允许为空!",
//                  
//              },
                relName : {
                    required:"姓名不允许为空!",
                    maxlength:"姓名长度不可以超过20",
                },
                idNumber : {
                    required:"身份证号不允许为空!",
                    maxlength:"身份证号长度不可以超过18",
                },
                userType : {
                    required:"用户类型不允许为空!"
                },
                division : {
                    required:"行政区划不允许为空!"
                }
			}
		});
	};

    // 缓存jquery对象
	var $userLevel = $("#userLevel"),	// 用户等级
		$userName = $("#userName"),		// 手机名
		$passWord = $("#passWord"),		// 密码
		$confirmPwd = $("#confirmPwd"),	// 确认密码
//		$mobilePhone = $("#mobilePhone"),	// 手机号
		$relName = $("#relName"),		// 姓名
		$idNumber = $("#idNumber"),		// 身份证号
		$userType = $("#userType"),	// 采集类型
		$unit = $("#unit"),	// 所属单位
		$form = $('#web_register_form'),		// 表单
		$register = $('#register'),	// 注册按钮
		$backLogin = $('#backLogin'),	// 返回登录页
		$errorTextWrap = $('#errorInfo');		// 错误信息

	// 初始化事件
    function initEvent() {
        // 注册按钮事件绑定
    	$register.bind('click', function(){
    		if($("#web_register_form").valid()){
    			submitForm();
    		}
    		
        });
        $backLogin.bind('click', function(){    		
    		window.location.href = getServer()+"/platform/home"
        });
        // 给用户名、密码、验证码绑定按回车触发登录提交事件
//      $userName.on("keypress", function(event){
//      	if (event.keyCode == '13') {
//      		submitForm();
//          }
//      });
//      $password.on("keypress", function(event){
//      	if (event.keyCode == '13') {
//      		submitForm();
//          }
//      });
    }

    // 表单提交
    function submitForm() {
    	// 先验证表单数据
//      if(!validate()) return;
        // 提交请求
    	$.ajax({
            url: getServer() + "/fw/user/user",
            type: "post",
            contentType:"application/json",
            data: JSON.stringify(getPostData()),
            dataType: "json",
            success: function (data) {
            	debugger;
            	if(data.code == 200){
	    		 	Util.alert(data.data,function(){                	
	                	window.location.href = getServer()+"/platform/home";              	
	                })
            	}else{
            		Util.alert(data.message,function(){   
            			
	                })
            	}
                
            }
        });
    }
	

    //输入框验证
//  function validate() {
//  	var result = true;
//  	var userName = $userName.val();
//  	var password = $password.val();
//  	if (LOGIN_CAPTCHA == 'true') {
//  		if($.trim(userName) == ''
//  			|| $.trim(password) == ''
//  			|| $.trim(captchaValue) == ''){
//
//  			result = false;
//  			setErrorText("请输入用户名、密码、验证码");
//			}
//  	} else {
//  		if($.trim(userName) == ''
//  			|| $.trim(password) == ''){
//
//  			result = false;
//  			setErrorText("请输入用户名、密码");
//			}
//  	}
//
//      return result;
//  };

    // 设置错误信息
    function setErrorText(text) {
    	$errorTextWrap.html(text);
    }


    // 表单内容清空
    function resetFrom() {
    	// 置空所有input
    	$form.find('input').val('');
    	// 登录名获取焦点
//      $userName.focus();
    };

    // 获取登录提交数据
    function getPostData() {
    	var userLevel = $.trim($userLevel.val());
    	var userName = $.trim($userName.val());
    	var confirmPwd = $.trim($confirmPwd.val());
//  	var mobilePhone = $.trim($mobilePhone.val());
    	var relName = $.trim($relName.val());
    	var idNumber = $.trim($idNumber.val());
    	var userType = $.trim($userType.val());
    	var unit = $.trim($unit.val()); 
    	var pwd = $.trim($passWord.val());
    	// 加密      
		debugger;
//      var encrypt = new JSEncrypt();
//      encrypt.setPublicKey(PUBLIC_KEY);
//      var pwd = encrypt.encrypt($.trim($passWord.val()));
//		console.log($("#divisionId").val());
        var data = {
            userLevel: userLevel,
            userName: userName,
//          mobilePhone: mobilePhone,
            relName: relName,
            idNumber: idNumber,
            userType: userType,
            unit: unit,
            pwd: pwd,
			division: $("#divisionId").val()
        };

        return data
    };
	var initdivision = function () {
    	$.ajax({
            url: getDivisionController() + 'initDivisionZtree',
            type: 'GET',
            success: function (res) {
            	var divisionData = res.data;
    			var combotree = Combotree({
		            // combo组件相关配置
		            combo: {
		                //要渲染的input的id
		                id: "division",
		                //下拉框的类型：单选or多选
		                multi: false,
		                key: {
		                    idKey: "divisionId",
		                    textKey: "divisionName"
		                },
		                // placeholder: "请选择……",
		                event: {
		                    onShowPanel: function () {
		                        console.log("show");
		                    },
		                    onHidePanel: function () {
		                        console.log("hide");
		                    },
		                    onChange: function (n, o) {
		                    	debugger;
		                    	if(n[0].divisionName=="中华人民共和国"){
		                    		Util.alert("请不要选择中华人民共和国",function(){
										$("#division").val('');
										$("#divisionId").val('');
									})

								}else {
									$("#divisionId").val(n[0].divisionId);
									$("#division").val(n[0].divisionName);
								}
		                    }
		                }
		            },
		            // ztree组件相关配置
		            ztree: {
		                data: {
		                    simpleData: {
		                        enable: true,
		                        idKey: "divisionId", // 主键属性名
		                        pIdKey: "parentId" // 父节点属性名
		                    },
		                    key: {
		                        name: "divisionName" // 显示名称属性名
		                    }
		                },
		                check: {
		                    chkboxType: {
		                        'Y': '',
		                        'N': ''
		                    }
		                }
		            },
		            data: divisionData,
		//            [
		//				    {
		//				        "divisionId":"root",
		//				        "divisionCode":"root",
		//				        "divisionName":"中华人民共和国",
		//				        "parentId":"",
		//				        "allParentId":"root",
		//				        "level":"0",
		//				        "divisionType":"Country",
		//				        "region":"",
		//				        "isValid":"1",
		//				        "createUser":"c8f1ba6c7cf842409aba43206e9f7442",
		//				        "createTime":"2020-05-08 19:20:03",
		//				        "updateUser":"c8f1ba6c7cf842409aba43206e9f7442",
		//				        "updateTime":"2020-05-08 19:20:03"
		//				    },
		//				    {
		//				        "divisionId":"c4cfce1d06bb402e92bd02c4426e018c",
		//				        "divisionCode":"010101",
		//				        "divisionName":"河北省",
		//				        "parentId":"root",
		//				        "allParentId":"root,c4cfce1d06bb402e92bd02c4426e018c",
		//				        "level":"1",
		//				        "divisionType":"",
		//				        "region":"NC",
		//				        "isValid":"1",
		//				        "createUser":"c8f1ba6c7cf842409aba43206e9f7442",
		//				        "createTime":"2020-05-14 10:31:30",
		//				        "updateUser":null,
		//				        "updateTime":null
		//				    }
		//				],
		            
		            formatter: function (node) {
		                node.open = false;
		            },
		            value: $("#divisionId").val(),
		            search: {
		                enable: true,
		                fields: ["divisionName"]
		            }
		        });
            }
        });

	}


    return {
    	init: init
    }
});